package com.dong.zk;


import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author: dzj
 * @date 2018/10/10-12:05
 */
public class ZkGetNodeData implements Watcher {
    private ZooKeeper zk = null;
    public static Logger logger = LoggerFactory.getLogger(ZkGetNodeData.class);
    public static final String zkServerPath = "10.0.109.142:2181";
    public static final Integer timeout=5000;

    private static Stat stat = new Stat();

    private static CountDownLatch cdl = new CountDownLatch(1);


    public ZkGetNodeData() {

    }

    public ZkGetNodeData(String path) {
    //    super(logger);
        try {
            zk = new ZooKeeper(path,timeout,new ZkNodeOperator());

        } catch (IOException e) {
            if(zk!=null) {
                try {
                    zk.close();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }

    public ZooKeeper getZk() {
        return zk;
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZkGetNodeData zkServer = new ZkGetNodeData(zkServerPath);
        byte[] data = zkServer.getZk().getData("/imooc", new ZkGetNodeData(), stat);
        String result = new String(data);
        System.out.println("当前值 : "+ result);
        cdl.await();

    }


    public void process(WatchedEvent watchedEvent) {
        try{
            if(watchedEvent.getType()== Event.EventType.NodeDataChanged) {
                ZkGetNodeData zkServer = new ZkGetNodeData(zkServerPath);
                byte[] datas = zkServer.getZk().getData("/imooc", false, stat);
                String result = new String(datas);
                System.out.println("更新后的值: "+result );
                System.out.println("版本号变化 dversion: "+stat.getVersion());
                cdl.countDown();

            }else if (watchedEvent.getType()== Event.EventType.NodeCreated) {

            }else if(watchedEvent.getType()==Event.EventType.NodeDeleted) {

            }else if (watchedEvent.getType()==Event.EventType.NodeChildrenChanged) {

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
 //       super.process(watchedEvent);

    }
}
